package com.sdkj.fixed.asset.assets.service;

import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.MaintenanceChangeAssetsExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.MaintenanceChangeExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.SelPrams;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseHistoryResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * @author niuliwei
 * @description 维保信息变更
 * @date 2020/7/27 10:51
 */
@Service
public class MaintenanceChangeService extends BaseService<MaintenanceChange> {

    @Autowired
    private MaintenanceChangeMapper changeMapper;
    @Autowired
    private MaintenanceChangeAssetsMapper changeAssetsMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Resource
    private AssetSupplierMapper assetSupplierMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private AssetLogMapper assetLogMapper;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WarehouseHistoryMapper historyMapper;
    @Override
    public BaseMapper getMapper() {
        return changeMapper;
    }

    //获取订单号
    private String getNumber(String key, String orgId) {
        Long incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        if (incr == 0) {
            incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        }
        DecimalFormat df = new DecimalFormat("0000");
        return key + DateTools.dateToString(new Date(), "yyyyMMdd") + df.format(incr);
    }

    /**
     * 维保信息变更-新增
     * @param change
     * @return
     */
    public MaintenanceChange add(MaintenanceChangeExtend change){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        change.setNumber(getNumber("WB", orgId));
        change.setDate(change.getDate());
        change.setIsDeleted(0);
        change.setCreateUser(userId);
        change.setCreateDate(TimeTool.getCurrentTimeStr());
        change.setUpdateUser(userId);
        change.setUpdateDate(TimeTool.getCurrentTimeStr());
        change.setOrgId(orgId);
        changeMapper.insertSelective(change);

        historyMapper.batchInsert(change.getAssetIdList() ,change.getId(),6);

        for (String str : change.getAssetIdList()) {
            //插入资产维保明细
            MaintenanceChangeAssets asset = new MaintenanceChangeAssets();
            asset.setMaintenanceInfoChangeId(change.getId());
            asset.setAssetId(str);
            asset.setIsDeleted(0);
            asset.setCreateUser(userId);
            asset.setCreateDate(TimeTool.getCurrentTimeStr());
            asset.setUpdateUser(userId);
            asset.setUpdateDate(TimeTool.getCurrentTimeStr());

            //查询资产变更前维保信息
            AssetSupplier assetSupplier = selByAssetId(str);
            if(assetSupplier != null){
                asset.setSupplierId(assetSupplier.getSupplierId());
                asset.setSupplierName(assetSupplier.getSupplierName());
                asset.setExpireDate(assetSupplier.getExpireTime());
                asset.setUser(assetSupplier.getSupplierUser());
                asset.setUserName(assetSupplier.getSupplierUser());
                asset.setNote(assetSupplier.getExplainText());

                //修改资产维保信息
                Example example = new Example(AssetSupplier.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("assetId", str);
                AssetSupplier supplier = new AssetSupplier();
                supplier.setSupplierId(change.getSupplierId());
                supplier.setSupplierName(change.getSupplierName());
                supplier.setSupplierUserId(change.getUser());
                supplier.setSupplierUser(change.getUserName());
                supplier.setExpireTime(change.getExpireDate());
                supplier.setExplainText(change.getNote());
                assetSupplierMapper.updateByExampleSelective(supplier, example);
            } else {
                AssetSupplier supplier = new AssetSupplier();
                supplier.setAssetId(str);
                supplier.setSupplierId(change.getSupplierId());
                supplier.setSupplierName(change.getSupplierName());
                supplier.setSupplierUserId(change.getUser());
                supplier.setSupplierUser(change.getUserName());
                supplier.setExpireTime(change.getExpireDate());
                supplier.setExplainText(change.getNote());
                assetSupplierMapper.insertSelective(supplier);
            }

            stateLog(str, "维保信息变更", assetSupplier, change, userId);

            changeAssetsMapper.insertSelective(asset);
        }

        return change;
    }

    /**
     * 查询资产供应商
     * @param assetId
     * @return
     */
    public AssetSupplier selByAssetId(String assetId){
        Example example = new Example(AssetSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("assetId", assetId);
        List<AssetSupplier> list =  assetSupplierMapper.selectByExample(example);
        if(list != null && list.size()>0){
            return list.get(0);
        }else {
            return null;
        }
    }

    /**
     * 维保信息变更-分页查询
     * @param param
     * @return
     */
    public List<MaintenanceChangeExtend> getAllPage(PageParams<SelPrams> param){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer i = reportMapper.selectUserIsAllDataAuth(userId);
        if(i==1){
            userId = null;
        }
        PageHelper.startPage(param.getCurrentPage(), param.getPerPageTotal());
        List<MaintenanceChangeExtend> list = changeMapper.getChange(param.getParams().getStartDate(), param.getParams().getEndDate(), orgId, userId, null);
        if(list != null && list.size()>0){
            for (MaintenanceChangeExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),6);
                extend.setResults(results);
            }
        }
        return list;
    }

    /**
     * 维保信息变更-查看详情
     * @param id
     * @return
     */
    public MaintenanceChangeExtend selById(String id){
        MaintenanceChangeExtend extend = changeMapper.selById(id);
        List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),6);
        extend.setResults(results);
        return extend;
    }

    /**
     * 维保信息变更-打印
     * @param id
     * @return
     */
    public MaintenanceChangeExtend print(String id){
        MaintenanceChangeExtend extend = changeMapper.selById(id);
        List<MaintenanceChangeAssetsExtend> assetList = changeMapper.selChangeBefor(id);
        extend.setMaintenanceChangeAssetsExtendist(assetList);
        return extend;
    }

    /**
     * 资产处理日志
     * @param assetId
     * @param modelName
     * @param assetSupplier
     * @param change
     */
    public void stateLog(String assetId, String modelName, AssetSupplier assetSupplier, MaintenanceChangeExtend change, String userId){
        Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetId);

        //资产处理日志记录
        LogContext log = new LogContext();

        if(assetSupplier == null){
            log.setBeforsupplierName("");
            log.setBeforsuppliercontact("");
            log.setBeforsupplierTel("");
            log.setBeforuserName("");
            log.setBeforexpireDate("");
            log.setBeforexpireNote("");
        }else {
            log.setBeforsupplierName(assetSupplier.getSupplierName());
            log.setBeforsuppliercontact(assetSupplier.getSupplierUser());
            log.setBeforsupplierTel(assetSupplier.getSupplierUser());
            log.setBeforuserName(assetSupplier.getSupplierUser());
            log.setBeforexpireDate(assetSupplier.getExpireTime());
            log.setBeforexpireNote(assetSupplier.getExplainText());
        }
        log.setAftersupplierName(change.getSupplierName());
        log.setAftersuppliercontact(change.getSuppliercontact());
        log.setAftersupplierTel(change.getSupplierTel());
        log.setAfteruserName(change.getUserName());
        log.setAfterexpireDate(change.getExpireDate());
        log.setAfterexpireNote(change.getNote());

        String logContent = "资产【"+warehouse.getAssetName()+"】"+ modelName +"处置；" +  ChangLogUtil.simpleLogContxt(log);

        AssetLog assetLog = new AssetLog();
        assetLog.setAssetId(assetId);
        assetLog.setLogType(modelName);
        assetLog.setHandlerId(userId);
        assetLog.setHandlerUser(change.getHandleUserName());
        assetLog.setHandlerContext(logContent);
        assetLog.setCreateUser(userId);
        assetLog.setCreateTime(TimeTool.getCurrentTimeStr());
        assetLogMapper.insertSelective(assetLog);
    }

}
